
//测试数据----用户数据
var usersData = new Array();
usersData = [{
    id: 1,
    name: "qq",
    password: 123,
    headImage:"assets/images/m_head.jpg"
}, {
    id: 2,
    name: "ww",
    password: 123,
    headImage:"assets/images/m_head2.jpg"
}];
trace("okok============")
//-----------------
//房间
//-----------------
//--------
//构造函数
//---------
var users_so=new Object();
users_so.onStatus=function(info){
	trace("存储users状态：");
	trace(info.level+" : "+info.code);
	}
function Room(type,number,limit){
    this.type = type || "common"; //普通版、视频版
    this.limit = limit || 3;//限制人数3
    this.number =number||Room.amount++;//房间号(等于当前房间的总数量)
    this.address ="rtmp://www.fcwr.com/fcwr/"+this.number;//房间地址
    this.isFull = false;//房间状态:是否满员
    this.status="ready"//房间状态:ready等待嘉宾准备、wait嘉宾准备完毕等待参赛者、starting游戏进行中
	//属性方法(函数伪装成属性)、动态属性、关联属性、冗余属性
    this.users_so;//关联用户存储
    this.users;//返回房间所有用户    
    this.userAmount;//返回房间用户数目
	var _users = function(){
        var usersAttr = new Array();
        if(application.users_so!=undefined){
	        var names=application.users_so.getPropertyNames();
            for (var i in names ) {
                usersAttr.push(application.users_so.getProperty(names[i]))
            }
          }
      return  usersAttr;//无缓存
    }
    var _userAmount = function(){
        return this.users.length;//无缓存
    }
	if(Room._initialized==undefined){
		Room.prototype.users=_users.call(this);
		Room.prototype.userAmount=_userAmount.call(this);    
		Room._initialized=true;    
	  }
}
//---
//静态属性
//------

Room.amount = 0;//房间总数
//-----
//类方法
//----
//是否存在空房间？
Room.hasEmptyRoom = function(type){
    var existEmptyRoomFlag = false;
    var rooms=Room.findByType(type);
    for (var i in rooms ) {
        var room = rooms[i];
        if (!room.isFull) {
            existEmptyRoomFlag = true;
            break;
        }
    }
    return existEmptyRoomFlag;
}
//根据房号查找房间
Room.findByNumber = function(number){
	 var names=application.rooms_so.getPropertyNames()
    for (i in names) {
        var room = application.rooms_so.getProperty(names[i]);
        trace("当前房间："+room.number)
        if (room.number.toString() == number.toString()) {
            return room;
        }
    }
    return null;
}
//获取当前最优先Room
Room.findMaxUserRoom = function(roomType){
    var sortedRoomLimts = new Array();
    //获取限制数集合
    var names=application.rooms_so.getPropertyNames()
    for (var i in names) {
        var room = application.rooms_so.getProperty(names[i]);
        //已经爆满的房间不参与排序
        if (!room.isFull&&room.type==roomType) {
            sortedRoomLimts.push(room.userAmount);
        }
    }
    //限制数排序
    sortedRoomLimts = sortedRoomLimts.sort();
    //返回当前用户最多的一个room
    return Room.findByUserAmount(roomType,sortedRoomLimts.slice(-1)[0]);
}
//根据属性查找对象attribute={userAmount:3}
Room.findByUserAmount = function(type,userAmount){
	 var names=application.rooms_so.getPropertyNames()
    for (var i in names) {
        var room = application.rooms_so.getProperty(names[i]);
        if (room.type==type&&room.userAmount == userAmount) {
            return room;
        }
    }
    return null;
}
//获取同一房间的其他用户
Room.getAnotherUsers = function(user){
    var AnotherUsers = new Array();
    for (var i = 0; i < application.clients.length; i++) {
        if (application.clients[i].id == user.id) {
            continue;
        }
        AnotherUsers.push(application.clients[i]);
    }
    return AnotherUsers;
}
//分配房间
Room.assignRoom = function(type){
    //当前是否有空的房间
    if (!Room.hasEmptyRoom(type)) {
        var room = new Room(type);
        trace("构造房间对象：" + room);
        room.save();
    }
    else {
         room = Room.findMaxUserRoom(type);//获取人数最多的房间
    }
    return room
}
//分配房间号
Room.assignRoomNumber = function(type){
    //当前是否有空的房间
    if (!Room.hasEmptyRoom(type)) {
      return   application.rooms_so.size()+1;
    }
    else {
        //获取人数最多的房间
        room = Room.findMaxUserRoom(type);
    }
    return room.number;
}
//根据类型查找房间
Room.findByType=function(type){
	var rooms=new Array();
		 var names=application.rooms_so.getPropertyNames()
    for (var i in names) {
        var room = application.rooms_so.getProperty(names[i]);
        if (room.type==type) {
            rooms.push(room);
        }
    }
    return rooms;
}
//创建或查找房间
Room.findOrCreateRoom=function(attributes){
   var room=application.rooms_so.getProperty(attributes["roomNumber"]);
    if(room==null){
	  room=new Room(attributes["type"],attributes["roomNumber"]);
	  application.rooms_so.setProperty(parseInt(attributes["roomNumber"]),room);
	trace("构造房间对象并持久化："+ application.rooms_so.getProperty(attributes["roomNumber"]).number);
	 }
   return room;
}
//-------
//实例方法
//-------
Room.prototype.destroy = function(){
    application.rooms_so.getProperty(this.number);
    application.rooms_so.setProperty(this, null);
    application.rooms_so.flush();
}
Room.prototype.save = function(){
    application.rooms_so.setProperty(this.number, this);
    application.rooms_so.flush();
    trace("持久化房间：" + this.number);
}
//查找房间内的用户

Room.prototype.findUserById = function(id){
    for (name in this.users_so.getPropertyNames()) {
        var user = this.users_so.getProperty(name);
        if (user.id == id) {
            return user;
        }
    }
    return null;
}


//--------
//用户
//---------
//-------
//构造函数
//-------
function User(attributes){
    //默认属性
    this.id = 2;
    this.age = 14;
    this.token="";
    this.type="actor";//用户类型：嘉宾、参赛者
    this.status;//用户状态：ready(嘉宾：等待参与者，参赛者：排队等待进入房间)
    //合并属性
    for (var attr in attributes) {
        this[attr] = attributes[attr] || this[attr]
    }
}

//----
//静态属性
//------

//------
//类方法
//-------
//查找数据库用户 TODO 连接数据库
User.findByNameDB = function(name){
    for (var i = 0; i < usersData.length; i++) {
        if (usersData[i].name == name) {
            return usersData[i];
        }
    }
    return false
}
//验证用户身份
User.validDB = function(loginInfo){
    var user = User.findByNameDB(loginInfo.userName);
    if (user && user.password.toString() == loginInfo.password.toString()) {
        return user
    }
    return false;
}
//查找用户attributes["room"]为房间对象
User.find=function(attributes){
	var room=attributes["room"];
	for(user in room.users){
		if(user.id.toString()==attributes[id].toString()){
			return user;
			}
		}
	return null;
	}

//-----
//实例方法
//------
//删除用户
User.prototype.destroy = function(){
    application.users_so.getProperty(this.id);
    application.users_so.setProperty(user,null);
}
//保存用户到指定房间(attributes["room"]房间对象)
User.prototype.save= function(){
	application.users_so.setProperty(this.id,this);
    trace("持久化用户：" + this+ " 到房间 " + "rtmp://www.fcwr.com/fcwr/" + this.roomNumber);
}

//---------------
//fms处理
//--------------
//应用实例启动时处理

application.onAppStart = function(){
    trace("启动应用实例：" + application.name)
    if (application.name == "fcwr/_definst_") {
        application.rooms_so = SharedObject.get("rooms", true);
        trace("建立房间存储：" + application.rooms_so.name + application.rooms_so);
        for (var name in application.rooms_so.getPropertyNames()) {
            trace("房间号：" + name);
        }
    }
    else {
        //代理房间存储
        var definstNc = new NetConnection();
        definstNc.connect("rtmp://www.fcwr.com/fcwr/_definst_");
        application.rooms_so = SharedObject.get("rooms", false, definstNc);
        trace("代理definist中的数据：" + application.rooms_so.name+ application.rooms_so.getPropertyNames())
        //设置房间消息存储区
        SharedObject.get("message", true);
        //绑定房间内的用户存储
        application.users_so = SharedObject.get("users", true);
        trace("房间内的用户存储：" + application.users_so);
    }
}

//应用实例关闭时处理
application.onAppStop=function(){
	//清除所有存储

}
/**
 * 连接请求/用户登录验证
 */
application.onConnect = function(client, info){
		 // 相册订阅通知 
		  client.notifyPhotoSubscriber=function(client){
		    var anotherUsers = Room.getAnotherUsers(client);
		    trace("订阅相册播报的人数：" + anotherUsers.length);
		    for (var i = 0; i < anotherUsers.length; i++) {
		        trace("发送相册订阅通知到" + anotherUsers[i].id)
		        anotherUsers[i].call("subscribePhoto", null, client.id);
		    }
		  }
	    //登陆后客户端获取房间号,登陆客户端获取封装的用户信息
	    client.getloginServerResult=function(roomType,userType){
		    var result;
            var roomNumber=Room.assignRoomNumber(info.roomType);
            var userInfo=new User(client.userInfo);
            result={roomNumber:roomNumber,userInfo:userInfo}
            return result;		    
		 }
    if (info && info["password"] != null) {
    trace("用户：" + info.userName + " 正在流向 " + application.name);
        //验证用户信息
        var userObject = User.validDB(info);
        trace("验证结果：" + userObject)
        if (userObject) {
	        client.userInfo=userObject;
		  application.acceptConnection(client);
        }
        else {
            var error = new Object();
            error.message = "用户名或密码错误！";
            application.rejectConnection(client, error);
        }
    }if(info&&info["xiaonei_session_key"]){
	  application.acceptConnection(client);//校内连接处理 TODO  
	}else {
        if (info && info.userInfo != null) {
	        var roomNumber=parseInt(application.name.split("/").slice(-1)[0]);
            //查找、创建房间
			application.room=Room.findOrCreateRoom({roomNumber:roomNumber,type:info.roomType});
            //构造用户并持久化到房间
            info.userInfo.clientId = client.id;
            info.userInfo.roomNumber=roomNumber;
            var user=new User(info.userInfo)
            user.save();
            //第二次请求，验证通过进入指定房间	
            application.acceptConnection(client);
            trace("用户：" + user.name + " 角色类型："+user.type+" 进入房间：" + application.room.number + " 当前房间人数：" + application.room.userAmount);
        }
        else {
            //存储连接
            trace(application.name + " 存储对象连接：" + client.id)
            application.acceptConnection(client);
        }
    }
}
application.onDisconnect = function(client){
    //删除退出连接的用户
        if (application.name != "fcwr/_definst_") {
           var user = User.find({clientId:client.id,room:application.room});
           user.destroy();
        trace("房间：" + room.number + " 删除用户：" + user.name)
       }
}
/**
 * 视频流通知订阅
 */
application.onPublish = function(client, origStream){
    var anotherUsers = Room.getAnotherUsers(client)
    trace("视频流：" + origStream.name + " 流向 " + application.name);
    //通知房间内的其他人订阅
    trace("其他人数：" + anotherUsers.length)
    for (var i = 0; i < anotherUsers.length; i++) {
        trace("发送通知到" + anotherUsers[i].id)
        anotherUsers[i].call("subscribeVideo", null, origStream.name);
    }
}

 
 
